const { UserInputError } = require("apollo-server-express");
const jwt = require("../util/jwt");
const md5 = require("../util/md5");
const { jwtSecret } = require("../config/config.default");

const userResolvers = {
  Query: {
    // 获取用户信息
    currentUser(parent, args, context, info) {
      return context.user;
    },
    foo(parent, args, context, info) {
      console.log(context.user);
      return "bar";
    },
  },

  Mutation: {
    // 注册
    async createUser(parent, { user }, { dataSources }) {
      const users = dataSources.users;
      const user1 = await users.findByEmail(user.email);
      if (user1) {
        throw new UserInputError("Email already exists");
      }
      const user2 = await users.findByUsername(user.username);
      if (user2) {
        throw new UserInputError("Username already exists");
      }

      const userData = await users.saveUser(user);
      const token = await jwt.sign(
        {
          userId: userData._id,
        },
        jwtSecret,
        { expiresIn: 60 * 60 * 24 }
      );
      return {
        user: {
          ...userData.toObject(),
          token,
        },
      };
    },

    // 登录
    async login(parent, { user }, { dataSources }) {
      const userData = await dataSources.users.findByEmail(user.email);
      if (!userData) {
        throw new UserInputError("邮箱不存在");
      }
      if (md5(user.password) !== userData.password) {
        throw new UserInputError("密码错误");
      }

      const token = await jwt.sign(
        {
          userId: userData._id,
        },
        jwtSecret,
        { expiresIn: 60 * 60 * 24 }
      );

      return {
        user: {
          ...userData.toObject(),
          token,
        },
      };
    },

    // 更新用户
    async updateUser(parent, { user: userInput }, { dataSources, user }) {
      if (userInput.password) {
        userInput.password = md5(userInput.password);
      }
      const ret = await dataSources.users.updateUser(user._id, userInput);
      return {
        user: ret,
      };
    },
  },
};

module.exports = userResolvers;
